"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 硬件故障类--CPU
Case Name   : 主节点启动时CPU占用率高
Create At   : 2021/07/08
@zou_jialiang0505328126
Description :
    1.主节点注入CPU占用率高故障
    ./cfe "inject rCPU_Overloadau (cpuid1, cpuid2, usage, time)
    values(1, 7, 99, 80)"
    2.并发连接数据库
    连接150个session，每个seesion执行以下指令：
    create table i_1(i int);
    insert into i_1 values(1);
Expect      :
    1.成功
    2.成功
History     :
    Modified by @wan005 2022/3/25:reboot主机及备1，规避环境因多次注入故障无法恢复问题
    Modified by wx1115623 2023/2/6:修改注入CPU占用率故障断言信息
    Modified by wx1115623 2023/2/20:修改CPU占用率故障注入语句，规避故障注入失败
"""

import unittest
import time
import os
from yat.test import Node
from testcase.utils.Common import Common
from testcase.utils.Constant import Constant
from testcase.utils.CommonSH import CommonSH
from testcase.utils.CommonSH import RestartDbCluster
from testcase.utils.Logger import Logger
from testcase.utils.ComThread import ComThread


class CPUOverloadAndRunTPCC(unittest.TestCase):
    nodes_tuple = ('PrimaryDbUser', 'Standby1DbUser', 'Standby2DbUser')

    @RestartDbCluster(*nodes_tuple)
    def setUp(self):
        self.log = Logger()
        self.log.info(f"-----{os.path.basename(__file__)} start-----")
        self.primary_root_node = Node(node='PrimaryRoot')
        self.primary_root_reboot = Node(node='PrimaryRoot')
        self.sta1_root_node = Node(node='Standby1Root')
        self.com = Common()
        self.constant = Constant()
        self.primary_sh = CommonSH('PrimaryDbUser')
        self.sta2_sh = CommonSH('Standby2DbUser')
        self.tb_name = "cpu_tb"
        self.db_name = "cpu_db"

    def test_main(self):
        self.log.info("--------------主节点注入CPU占用率高故障-------------")
        self.primary_root_reboot.sh('reboot')
        self.sta1_root_node.sh('reboot')
        for i in range(15):
            time.sleep(120)
            self.sta2_sh.stopDbCluster()
            self.sta2_sh.startDbCluster()
            result = self.sta2_sh.getDbClusterStatus('status')
            if result:
                break

        time.sleep(30)
        shell_cmd = "cat /proc/cpuinfo |grep 'processor'|wc -l"
        self.log.info(shell_cmd)
        cpu_num = self.primary_root_node.sh(shell_cmd).result()
        self.log.info(cpu_num)
        inject_command = f"rCPU_Overloadau (cpuid1, cpuid2, usage, time) " \
            f"values(0, {int(cpu_num)-1}, 99, 80)"
        result = self.com.cfe_inject(self.primary_root_node, inject_command)
        self.log.info(result)
        flag = self.constant.cfe_inject_rcpu_overloadau_success_msg in result
        if not flag:
            res = self.com.cfe_inject(self.primary_root_node, inject_command)
            self.log.info(res)
            self.assertIn(self.constant.cfe_inject_rcpu_overloadau_success_msg,
                          res.strip())

        self.log.info("-------------2.并发连接数据库---------------")
        connect_thread = []
        sql = f"create database {self.db_name};"
        result = self.primary_sh.executDbSql(sql)
        self.log.info(result)
        self.assertIn(self.constant.CREATE_DATABASE_SUCCESS_MSG, result)
        for i in range(150):
            sql = f"select pg_sleep(0.5); " \
                f"create table if not exists {self.tb_name}{i}(i int);" \
                f"insert into {self.tb_name}{i} " \
                f"values(generate_series(1,90000));"
            connect_thread.append(ComThread(
                self.primary_sh.executDbSql, args=(sql, self.db_name, '')))
            connect_thread[i].setDaemon(True)
            connect_thread[i].start()

        self.log.info("----------------检查线程结果------------------")
        for i in range(150):
            connect_thread[i].join(600)
            result = connect_thread[i].get_result()
            self.log.info(result)
            self.assertIn('INSERT', result)
            self.assertIn('CREATE', result)

    def tearDown(self):
        self.log.info("------------删除数据库-----------")
        time.sleep(80)
        sql = f"drop database if exists {self.db_name};"
        result = self.primary_sh.executDbSql(sql)
        self.log.info(result)
        self.log.info(f"-----{os.path.basename(__file__)} end-----")
